<?php 
namespace app\api\controller;

use app\common\server\Redispool;
use GuzzleHttp\Client;
use GuzzleHttp\Cookie\CookieJar;
class SaveWxlogin{
    private static $key = ['wx1'=>'377837240@qq.com','wx2'=>'1596114905@qq.com'];
    private static $redis = '';

    public function __construct(){
        $conf = [
            'redis_conf'=>[
                '127.0.0.1',6379,''     //定义Redis配置
            ],
        ];

        Redispool::addServer($conf);
        self::$redis = Redispool::getRedis('redis_conf',7);
    }

    private function _getCookie($key){
        $cookie_arr = self::$redis->hgetall('weixinpublic:'.$key.'_cookie');
        $cookie='';
        foreach ($cookie_arr as $k=>$v){
            $cookie .= $k.'='.$v.';';
        }
        return  $cookie;
    }


    private function _getToken($key){
        return self::$redis->get('weixinpublic:'.$key.'_token');
    }


    private function fetch($key,$username){
        $headers = [
            'headers' => [
                'Accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
                'Accept-Encoding' => 'gzip, deflate, br',
                'Accept-Language' => 'zh-CN,zh;q=0.9',
                'Cache-Control' => 'max-age=0',
                'Host' => 'mp.weixin.qq.com',
                'Referer' => 'https://mp.weixin.qq.com/cgi-bin/bizlogin?action=validate&lang=zh_CN&token=&account='.$username,
                'User-Agent' => 'Mozilla/5.0 (Linux; U; Android 4.4.3; zh-cn; HTC 802w Build/KTU84L) AppleWebKit/533.1 (KHTML, like Gecko)Version/4.0 MQQBrowser/5.4 TBS/025489 Mobile Safari/533.1 MicroMessenger/6.3.13.49_r4080b63.740 NetType/WIFI Language/zh_CN',
                'Connection' => 'keep-alive'
            ],
            'verify'=>false
        ];


        $headers['headers']['Cookie']=$this->_getCookie($key);
        $jar = new CookieJar();
        $headers['cookies']=$jar;

        $url = 'https://mp.weixin.qq.com/cgi-bin/home';


        $headers['query'] =  ['lang'=>'zh_CN','t'=>'home/index','token'=>$this->_getToken($key)];

//        $headers['form_params'] = ["lang"=>"zh_CN","f"=>"json","ajax"=>1,"random"=>"0.".mt_rand(100000000, 999999999),"token"=>""];

        $client = new Client();
        $response= $client->request('GET',$url,$headers);


        if($response->getStatusCode() == 200){
            if(isset($jar)){
                $this->set_cookies($jar,$key);
            }
        }

        return true;
    }


  	public function save(){
         foreach (self::$key as $k=>$v){
             sleep(10);
             $this->fetch($k,$v);
         }
         echo '保持成功';
   	}


    private  function set_cookies($jar,$key){
        $cookies_arr = $jar->toArray();

        foreach ($cookies_arr as $cookie) {
            self::$redis->hset('weixinpublic:'.$key.'_cookie',$cookie['Name'],$cookie['Value'] );
        }

        return true;
    }


}